<template>
	<view class="dict-tag">
		<block v-for="(item, index) in options" :key="index">
			<!-- 匹配项 -->
			<block v-if="values.includes(item.dictValue)">
				<text v-if="(item.listClass === 'default' || item.listClass === '') && (!item.cssClass)"
					:class="item.cssClass">
					{{ item.dictLabel }}
				</text>
				<view v-else class="tag">
					{{ item.dictLabel }}
				</view>
			</block>
		</block>
		<!-- 未匹配项 -->
		<view v-if="unmatch && showValue" class="unmatch">
			{{ unmatchArray | handleArray }}
		</view>
	</view>
</template>

<script>
	export default {
		name: "DictTag",
		props: {
			options: {
				type: Array,
				default: () => [],
			},
			value: {
				type: [Number, String, Array],
				default: null,
			},
			showValue: {
				type: Boolean,
				default: true,
			},
			separator: {
				type: String,
				default: ",",
			},
		},
		data() {
			return {
				unmatchArray: [], // 未匹配项
			};
		},
		computed: {
			values() {
				if (this.value === null || typeof this.value === "undefined" || this.value === "") return [];
				return Array.isArray(this.value) ?
					this.value.map((item) => "" + item) :
					String(this.value).split(this.separator);
			},
			unmatch() {
				this.unmatchArray = [];
				if (!this.value || this.options.length === 0) return false;
				let hasUnmatch = false;
				this.values.forEach((item) => {
					if (!this.options.some((v) => v.dictValue === item)) {
						this.unmatchArray.push(item);
						hasUnmatch = true;
					}
				});
				return hasUnmatch;
			},
		},
		filters: {
			handleArray(array) {
				return array.length === 0 ? "" : array.join(" ");
			},
		},
	};
</script>

<style>
	/* 标签样式 */
	.tag {
		/* padding: 5px 10px; */
		border-radius: 5px;
		display: inline-block;
		/* margin-right: 10px; */
		font-size: 14px;
	}

	.tag-primary {
		background-color: #007aff;
		color: #fff;
	}

	.tag-success {
		background-color: #4caf50;
		color: #fff;
	}

	.tag-default {
		background-color: #e0e0e0;
		color: #333;
	}

	.unmatch {
		margin-top: 10px;
		color: #ff5722;
	}
</style>